package pl.edu.agh.gt.data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RatesHistory {

	public String name;
	protected Map<Date, Rate> ratesMap = Collections.synchronizedMap(new HashMap<Date, Rate>());
	protected List<Rate> ratesList = Collections.synchronizedList(new ArrayList<Rate>());

	public RatesHistory(String n) {
		this.name = n;
	}

	public Rate getRate(Date time) {
		return ratesMap.get(time);
	}
	
	public Rate getRate(int index) {
		return ratesList.get(index);
	}

	public RatesHistory getPeriod(Date start, Date end) {
		
		RatesHistory newRates = new RatesHistory(name);
		
		for(Rate r : ratesList) {
			if(r.getTime().after(start) && r.getTime().before(end))
				newRates.addNextRate(r);
		}
		
		return newRates;
	}
	
	public List<Rate> asSortedList () {		
		return ratesList;
	}

	public void addNextRate(Rate rate) {
		assert ratesList.size() > 0 ? rate.getTime().after(ratesList.get(ratesList.size()-1).getTime()) : true;
		ratesList.add(rate);
		ratesMap.put(rate.getTime(), rate);
	}

	public Rate getLastRate() {
		return ratesList.get(ratesList.size()-1);
	}
}
